package com.cherish.meeting.api.service.impl;

import com.cherish.meeting.api.service.IUserInfoService;
import com.cherish.meeting.api.service.WxService;
import com.cherish.meeting.common.exception.BussException;
import com.cherish.meeting.common.util.StringUtil;
import com.cherish.meeting.db.entity.UserInfo;
import com.cherish.meeting.db.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-03-02
 */
@Slf4j
@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxService wxService;

    @Override
    public UserInfo selectByOpenid(String openid) {
        return userInfoMapper.selectByOpenid(openid);
    }

    @Override
    public UserInfo saveOrUpdate(UserInfo userInfo) throws BussException {
        UserInfo oldUser = userInfoMapper.selectByOpenid(userInfo.getOpenid());
        if (null == userInfo) {
            throw new BussException("未能获取到用户信息");
        }
        if (null == oldUser) {
            userInfoMapper.insert(userInfo);
            return userInfoMapper.selectByOpenid(userInfo.getOpenid());
        }
        if (userInfo.isSameTo(oldUser)) {
            throw new BussException("当前用户信息与系统输入一致");
        } else {
            userInfoMapper.updateByOpenId(userInfo);
            return userInfoMapper.selectByOpenid(userInfo.getOpenid());
        }
    }
}
